<html>
 <!--
 	@title  Auto-Reload
 	@author Jean-Lou Dupont
 	@desc   Background page for Auto-Reload
  -->
	<head>
		<script>
			var pageActionId = "auto_reload";
			var tabParams = {};
			var icons  = {"true": 1, "false": 0};
			var titles = {"true": "Click to stop auto-reload", 
						"false":"Click to start auto-reload"};
		
			chrome.extension.onConnect.addListener(function(port) {				
					console.log("* Auto-Reload: on-connect, tabId:"+port.tab.id);
					
			    	var tid=port.tab.id;
			    	var params=tabParams[tid] || {};
					var state=params["state"] || false;

					params["port"] = port;
					tabParams[tid] = params;

					//we just received this 'connect' request so
					//the port must be ok to use: assume safe.
					port.postMessage(state);
				    
			        chrome.pageActions.enableForTab(
			            pageActionId, {tabId: tid,
			            				url: port.tab.url,
										title: titles[String(state)],
										iconId: icons[String(state)]});
			});

			chrome.pageActions[pageActionId].addListener(function(paId, pageActionInfo) {
				console.log("! Auto-Reload: action clicked.");
				
			    chrome.windows.getCurrent(function(window) {
			      chrome.tabs.get(pageActionInfo.tabId, function(tab) {
			        // We need to know if we are the active window, because the tab may
			        // have moved to another window and we don't want to execute this
			        // action multiple times.
				        if (window.focused) {
					        var params=tabParams[tab.id] || {};
					        var state=params["state"] || false;
					        var port=params["port"] || null;
					        var new_state=state ? false:true;
					        var new_params={"state": new_state, "port":port};
					        tabParams[tab.id] = new_params;
					        console.log( new_params );
					        if (port) {
						        port.postMessage(new_state);
						        console.log("* Auto-Reload: Sent Message - tabId<"+tab.id+">  state<"+new_state+">");

						        chrome.pageActions.enableForTab(
							            pageActionId, {tabId: tab.id,
							            				url: port.tab.url,
														title: titles[String(new_state)],
														iconId: icons[String(new_state)]});
					        } else {
								console.log("! Auto-Reload: CANNOT send - tabId<"+tab.id+">  state<"+new_state+">");
					        }
				        } else {
					        console.log("* Auto-Reload: window not focused");
				        }
					});
				});
			});
			  
		</script>
	</head>
</html>